<?php

namespace app\common\model;

use think\facade\Db;

/**
 * 每日财务统计
 */
class FinanceStat
{
    /**
     * 插入成功订单明细
     */
    public static function addSuccessRecord($params)
    {
        // 不能重复插入
        $exists = Db::name('finance_detail')
            ->where('order_id', $params['order_id'])
            ->where('order_type', $params['order_type'])
            ->value('id');
        if ($exists) {
            return true;
        }

        // 财务明细
        Db::name('finance_detail')
            ->insert([
                'order_id' => $params['order_id'],
                'order_type' => $params['order_type'],
                'settle_type' => $params['settle_type'],
                'amount' => $params['amount'],
                'sale_price' => $params['sale_price'],
                'settle_price' => $params['settle_price'],
                'supplier_price' => $params['supplier_price'],
                'profit' => $params['profit'],
                'platform_profit' => $params['platform_profit'],
                'supplier_id' => $params['supplier_id'],
                'agent_id' => $params['agent_id'],
                'remark' => $params['remark'],
                'salesman_id' => $params['salesman_id'] ?? 0,
                'stat_time' => 1, // 待汇总到 finance_daily 和 agent_finance_daily
            ]);
    }

    /**
     * 汇总 finance_detail 数据 到 finance_daily 和 agent_finance_daily
     */
    public static function runStat()
    {
        $list = Db::name('finance_detail')
            ->where('stat_time', 1)
            ->limit(210)
            ->select()
            ->toArray();
        if (empty($list)) {
            echo '没啥的' . PHP_EOL;
            return true;
        }

        $total = [];
        $agent = [];
        $ids = [];
        $salesmanInfoArr = [];  // 业务员信息
        foreach ($list as $v) {
            $ids[] = $v['id'];
            $date = substr($v['created_at'], 0, 10);
            if (!isset($total[$date])) {
                $total[$date]['income'] = 0;
                $total[$date]['payout'] = 0;
            }
            if (!isset($agent[$v['agent_id']][$date])) {
                $agent[$v['agent_id']][$date]['income'] = 0;
                $agent[$v['agent_id']][$date]['payout'] = 0;
            }

            $total[$date]['income'] += $v['settle_price'];
            $total[$date]['payout'] += $v['supplier_price'];
            $agent[$v['agent_id']][$date]['income'] += $v['sale_price'];
            $agent[$v['agent_id']][$date]['payout'] += $v['settle_price'];

            // 业务员
            $salesmanId = $v['salesman_id'];
            if ($salesmanId > 0) {
                $orderType = $v['order_type'];
                if (!isset($salesmanInfoArr[$salesmanId][$orderType][$date])) {
                    $salesmanInfoArr[$salesmanId][$orderType][$date]['amount'] = 0;
                    $salesmanInfoArr[$salesmanId][$orderType][$date]['order_total'] = 0;
                }

                $salesmanInfoArr[$salesmanId][$orderType][$date]['amount'] += $v['sale_price'];  // 统计的是 销售价 单位分
                $salesmanInfoArr[$salesmanId][$orderType][$date]['order_total'] += 1;  // 订单数+1
            }
        }
        unset($list);

        Db::startTrans();
        try {
            Db::name('finance_detail')
                ->whereIn('id', $ids)
                ->update([
                    'stat_time' => time(),
                ]);

            // 平台财务统计
            foreach ($total as $date => $v) {
                $dailyId = Db::name('finance_daily')
                    ->where('dateymd', $date)
                    ->value('id');
                if ($dailyId) {
                    Db::name('finance_daily')
                        ->where('id', $dailyId)
                        ->inc('income', $v['income'])
                        ->inc('payout', $v['payout'])
                        ->update();
                } else {
                    Db::name('finance_daily')
                        ->insert([
                            'dateymd' => $date,
                            'income' => $v['income'],
                            'payout' => $v['payout'],
                        ]);
                }
            }

            // 代理商财务统计
            foreach ($agent as $agentId => $v) {
                foreach ($v as $date => $v2) {
                    $agentDailyId = Db::name('agent_finance_daily')
                        ->where('agent_id', $agentId)
                        ->where('dateymd', $date)
                        ->value('id');
                    if ($agentDailyId) {
                        Db::name('agent_finance_daily')
                            ->where('id', $agentDailyId)
                            ->inc('income', $v2['income'])
                            ->inc('payout', $v2['payout'])
                            ->update();
                    } else {
                        Db::name('agent_finance_daily')
                            ->insert([
                                'agent_id' => $agentId,
                                'dateymd' => $date,
                                'income' => $v2['income'],
                                'payout' => $v2['payout'],
                            ]);
                    }
                }
            }

            // 业务员业绩统计
            if ($salesmanInfoArr) {
                SalesmanFinanceDaily::runStat($salesmanInfoArr);
            }

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            echo '报错了：' . $e->getMessage() . PHP_EOL;
        }

        echo '成功汇总 ' . count($ids) . ' 条记录' . PHP_EOL;
    }
}
